package com.dong.common.util;

import com.dong.common.constant.PropertiesConst;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-08-27 16:11
 */
public class FileUtils {

    /**
     * 保存图片
     * @param dirName 文件夹名（菜单id）
     * @param filename 要保存的图片路径
     * @return 保存后的相对路径
     */
    public static String saveImage(String dirName, String filename) {
        String dirPath = PropertiesUtils.getValue(PropertiesConst.FILE_CONFIG_NAME, PropertiesConst.FILE_KEY_FOODDIR);
//        String path = FileUtils.class.getClassLoader().getResource(".").getPath() + dirPath + "/" + dirName;
        String path = dirPath + "/" + dirName;

        // 获取后缀
        String ext = filename.substring(filename.lastIndexOf("."));
        // 获取文件名
        String destFilename = "" + System.nanoTime() + System.currentTimeMillis() + ext;

        // 文件夹
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 文件
        File destFile = new File(dirFile, destFilename);

        // 复制文件
        copyFile(filename, destFile.getAbsolutePath());

        return dirPath + "/" + dirName + "/" + destFilename;
    }

    /**
     * 复制文件
     * @param srcPath 原文件路径
     * @param destPath 目标文件路径
     */
    public static void copyFile(String srcPath, String destPath){
        File src = new File(srcPath);
        File dest = new File(destPath);

        // 判断parent目录是否不存在
        if (!dest.getParentFile().exists()) {
            // 是：创建目录
            dest.getParentFile().mkdirs();
        }

        try (
                FileInputStream in = new FileInputStream(src);
                FileOutputStream out = new FileOutputStream(dest);
        ){
            byte[] data = new byte[1024 * 8];
            int len = -1;
            while((len = in.read(data)) != -1){
                out.write(data, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
